package com.xyxy.platform.openapi.common.web.bind.method;

import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.service.member.vo.SimpleMember;
import com.xyxy.platform.openapi.AppConstants;
import com.xyxy.platform.openapi.common.exception.RestException;
import com.xyxy.platform.openapi.common.web.bind.annotation.CurrentLoginMember;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * <p>用于绑定@FormModel的方法参数解析器
 * <p>Version: 1.0
 */
public class CurrentMemberMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private SpyMemcachedClient memcachedClient;

    public CurrentMemberMethodArgumentResolver() {
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasParameterAnnotation(CurrentLoginMember.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader(AppConstants.REQUEST_TOKEN_KEY);
        SimpleMember currentMember = null;
        if (StringUtils.isNotEmpty(token)) {
            currentMember = memcachedClient.get(token);
        }
        if (null == currentMember) {
            throw new RestException("没有找到 token, 请确定是否标注权限验证注解: @RequiresPermissions");
        }
        return currentMember;
    }
}
